<?php
namespace app\api\model\kuerp;

use think\Model;
use think\Db;
use Exception;
class UserAddress extends Model
{

    // 表名
    protected $name = 'kuerp_user_address';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取地址详情
     * @param int $id
     * @return array
     */
    public static function getArea($id){
        $area = (new Areas())->where(['id'=>$id])->find();
        if($area){
            return ['status'=>200,'msg'=>$area];
        }else{
            return ['status'=>500,'msg'=>'Query failed'];
        }
    }

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit,$user_id){
        $app_page = config('app_page');
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where,$user_id) {
                $query->where($where);
                $query->where('user_id', '=', $user_id);
            })->page($page,$limit)->field("id,connect_name,connect_mobile,province,city,area,detail_address,is_default,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where,$user_id) {
                $query->where($where);
                $query->where('user_id', '=', $user_id);
            })->field("id,connect_name,connect_mobile,province,city,area,detail_address,is_default,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->select())->toArray();
        }

        foreach ($list as $list_k=>$list_v){
            $area = self::getArea($list_v['province']);
            if($area['status']==200){
                $list[$list_k]['province_name'] = $area['msg']['name'];
            }

            $area = self::getArea($list_v['city']);
            if($area['status']==200){
                $list[$list_k]['city_name'] = $area['msg']['name'];
            }

            $area = self::getArea($list_v['area']);
            if($area['status']==200){
                $list[$list_k]['area_name'] = $area['msg']['name'];
            }
        }

        $count = self::where(function ($query) use ($where,$user_id) {
            $query->where($where);
            $query->where('user_id', '=', $user_id);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param int $id
     * @return array
     */
    public static function getDetail($id,$user_id){
        $detail = self::where(function ($query) use ($id,$user_id) {
            $query->where('id', '=', $id);
            $query->where('user_id', '=', $user_id);
        })->field("id,connect_name,connect_mobile,province,city,area,detail_address,is_default,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->find();

        if(empty($detail)){
            return ['status'=>500,'msg'=>'No shipping address found'];
        }

        $area = self::getArea($detail['province']);
        if($area['status']==200){
            $detail['province_name'] = $area['msg']['name'];
        }

        $area = self::getArea($detail['city']);
        if($area['status']==200){
            $detail['city_name'] = $area['msg']['name'];
        }

        $area = self::getArea($detail['area']);
        if($area['status']==200){
            $detail['area_name'] = $area['msg']['name'];
        }

        return ['status'=>200,'msg'=>$detail];
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail,$user_id){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'Parameter error'];
        }else{
            $check = (new \app\api\model\kuerp\UserAddress)->checkParameter($detail,[
                'connect_name|联系人'=>'require',
                'connect_mobile|手机'=>'require|number',
                'province|省'=>'require|number',
                'city|市'=>'require|number',
                'detail_address|详细地址'=>'require',
                'is_default|是否默认'=>'require|in:0,1',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                //验证用户
                $user = (new KuerpUser())->where(['id'=>$user_id])->find();
                if(empty($user)){
                    return ['status'=>500,'msg'=>'User not found'];
                }
                if($user['status']!='normal'){
                    return ['status'=>500,'msg'=>'User status异常'];
                }
                $detail['user_id'] = $user_id;

                $area = new Areas();

                if($detail['province']>100000){
                    $province = $area->where(['adcode'=>$detail['province']])->value('id');
                }else{
                    $province = $area->where(['id'=>$detail['province']])->value('id');
                }
                if(empty($province)){
                    return ['status'=>500,'msg'=>'Please select provincial data'];
                }
                $detail['province'] = $province;

                if($detail['city']>100000){
                    $city = $area->where(['adcode'=>$detail['city']])->value('id');
                }else{
                    $city = $area->where(['id'=>$detail['city']])->value('id');
                }
                if(empty($city)){
                    return ['status'=>500,'msg'=>'Please select city data'];
                }
                $detail['city'] = $city;

                if(isset($detail['area']) && !empty($detail['area'])){
                    if($detail['area']>100000){
                        $area = $area->where(['adcode'=>$detail['area']])->value('id');
                    }else{
                        $area = $area->where(['id'=>$detail['area']])->value('id');
                    }
                    if(empty($area)){
                        return ['status'=>500,'msg'=>'Area data error'];
                    }
                    $detail['area'] = $area;
                }

                $model = new \app\api\model\kuerp\UserAddress;
                $res = false;
                Db::startTrans();
                try {
                    if($detail['is_default']==1){
                        $model->where(['is_default'=>'1'])->update(['is_default'=>'0']);
                    }
                    $res = $model->allowField(true)->save($detail);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                }

                if($res){
                    return ['status'=>200,'msg'=>$model->id];
                }else{
                    return ['status'=>500,'msg'=>'Add failed'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail,$user_id){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'Parameter error'];
        }else{
            $check = (new \app\api\model\kuerp\UserAddress)->checkParameter($detail,[
                'id|ID'=>'require|number',
                'connect_name|联系人'=>'require',
                'connect_mobile|手机'=>'require|number',
                'province|省'=>'require|number',
                'city|市'=>'require|number',
                'detail_address|详细地址'=>'require',
                'is_default|是否默认'=>'require|in:0,1',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $model = new \app\api\model\kuerp\UserAddress;
                $row = $model->where(['id'=>$detail['id']])->find();;
                if($row){
                    //验证用户
                    $user = (new KuerpUser())->where(['id'=>$user_id])->find();
                    if(empty($user)){
                        return ['status'=>500,'msg'=>'User not found'];
                    }
                    if($user['status']!='normal'){
                        return ['status'=>500,'msg'=>'User status abnormal'];
                    }
                    if($user_id!=$row['user_id']){
                        return ['status'=>500,'msg'=>'You have no authority to modify'];
                    }
                    $detail['user_id'] = $user_id;

                    $area = new Areas();

                    if($detail['province']>100000){
                        $province = $area->where(['adcode'=>$detail['province']])->value('id');
                    }else{
                        $province = $area->where(['id'=>$detail['province']])->value('id');
                    }
                    if(empty($province)){
                        return ['status'=>500,'msg'=>'Please select provincial data'];
                    }
                    $detail['province'] = $province;

                    if($detail['city']>100000){
                        $city = $area->where(['adcode'=>$detail['city']])->value('id');
                    }else{
                        $city = $area->where(['id'=>$detail['city']])->value('id');
                    }
                    if(empty($city)){
                        return ['status'=>500,'msg'=>'Please select city data'];
                    }
                    $detail['city'] = $city;

                    if(isset($detail['area']) && !empty($detail['area'])){
                        if($detail['area']>100000){
                            $area = $area->where(['adcode'=>$detail['area']])->value('id');
                        }else{
                            $area = $area->where(['id'=>$detail['area']])->value('id');
                        }
                        if(empty($area)){
                            return ['status'=>500,'msg'=>'Area data error'];
                        }
                        $detail['area'] = $area;
                    }

                    $res = false;
                    Db::startTrans();
                    try {
                        if($detail['is_default']==1){
                            $model->where(['is_default'=>'1','id'=>['<>',$detail['id']]])->update(['is_default'=>'0']);
                        }
                        $res = $row->allowField(true)->save($detail);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                    }

                    if($res){
                        return ['status'=>200,'msg'=>'Update successful'];
                    }else{
                        return ['status'=>500,'msg'=>'Update failed'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'No data to update found'];
                }
            }
        }
    }

    /**
     * 删除
     * @param int $id
     * @return array
     */
    public static function delDetail($id,$user_id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'Parameter error'];
        }else{
            $model = new \app\api\model\kuerp\UserAddress;
            $list = $model->where(['id'=>['in',$id]])->select();;

            //验证用户
            $user = (new KuerpUser())->where(['id'=>$user_id])->find();
            if(empty($user)){
                return ['status'=>500,'msg'=>'User not found'];
            }
            if($user['status']!='normal'){
                return ['status'=>500,'msg'=>'User status abnormal'];
            }
            foreach ($list as $list_k=>$list_v){
                if($user_id!=$list_v['user_id']){
                    return ['status'=>500,'msg'=>'You have no authority to delete'];
                }
            }

            $res = $model->where(['id'=>['in',$id]])->delete();
            if($res){
                return ['status'=>200,'msg'=>$res];
            }else{
                return ['status'=>500,'msg'=>'Delete failed'];
            }
        }
    }

    public function checkParameter($data,$parameter){
        if(is_array($parameter)){
            foreach ($parameter as $parameter_k=>$parameter_v){
                if(strpos($parameter_k,'|') !== false){
                    $k = explode('|',$parameter_k);
                    $name = $k[1];
                    $variable = $k[0];
                }else{
                    $name = $parameter_k;
                    $variable = $parameter_k;
                }
                $parameter_v = empty($parameter_v)?'require':$parameter_v;
                $rule = explode('|',$parameter_v);
                foreach ($rule as $rule_k=>$rule_v){
                    if($rule_v=='requireNone'){
                        if(!isset($data[$variable])){
                            return ['status'=>400,'msg'=>'Please enter '.$name.' parameter'];
                        }
                    }else if($rule_v=='require'){
                        if(!isset($data[$variable]) || $data[$variable]===''){
                            return ['status'=>400,'msg'=>$name.' parameter is incorrect'];
                        }
                    }else{
                        $rule_row = explode(':',$rule_v);
                        switch ($rule_row[0]){
                            case 'in':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if(!isset($rule_row[1])){
                                        return ['status'=>300,'msg'=>'Validation rule error'];
                                    }
                                    $row_box = explode(',',$rule_row[1]);
                                    if(!in_array($data[$variable],$row_box)){
                                        return ['status'=>400,'msg'=>$name.' parameter is incorrect'];
                                    }
                                }
                                break;
                            case 'between':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if(!isset($rule_row[1])){
                                        return ['status'=>300,'msg'=>'Validation rule error'];
                                    }
                                    $row_box = explode(',',$rule_row[1]);
                                    if($data[$variable]<$row_box[0] || $data[$variable]>$row_box[1]){
                                        return ['status'=>400,'msg'=>$name.' parameter is incorrect'];
                                    }
                                }
                                break;
                            case 'number':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if (!preg_match("/^\d*$/", $data[$variable])){
                                        return ['status'=>400,'msg'=>$name.' can only be a number'];
                                    }
                                }
                                break;
                            case 'letter':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if (!preg_match("/^[a-zA-Z]+$/u", $data[$variable])){
                                        return ['status'=>400,'msg'=>$name.' can only be letters'];
                                    }
                                }
                                break;
                            case 'money':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if (!preg_match("/^[0-9]+(.[0-9]{1,4})?$/", $data[$variable])){
                                        return ['status'=>400,'msg'=>$name.' format error'];
                                    }
                                }
                                break;
                            case 'length':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if(!isset($rule_row[1])){
                                        return ['status'=>300,'msg'=>'Validation rule error'];
                                    }
                                    $row_box = explode(',',$rule_row[1]);
                                    if(strlen($data[$variable])<$row_box[0] || strlen($data[$variable])>$row_box[1]){
                                        return ['status'=>400,'msg'=>$name.' character length is between '.$row_box[0].'-'.$row_box[1].' characters'];
                                    }
                                }
                                break;
                            default:
                                return ['status'=>300,'msg'=>'Validation rule error'];
                        }
                    }
                }
            }
        }else{
            $parameter = explode(',',$parameter);
            foreach ($parameter as $k=>$v){
                if(!isset($data[$v]) || $data[$v]===''){
                    return ['status'=>400,'msg'=>'Parameter error'];
                }
            }
        }
        return true;
    }
}
